﻿using System;
using System.Text;
using System.Drawing;
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;

public static partial class NativeAOT
{
    [UnmanagedCallersOnly(EntryPoint = "atkn")]
    public static unsafe int atkn(IntPtr x_ptr, double eps, IntPtr f_x_ptr, int inter)
    {
        double* x = (double*)x_ptr.ToPointer();
        f_x = Marshal.GetDelegateForFunctionPointer<delegatefunc_x>(f_x_ptr);

        return atkn(x, eps, inter);
    }

    /// <summary>
    /// 方程求根aitken迭代法
    /// 函数由代理函数；
    /// </summary>
    /// <param name="x">x存放方程根的初值。返回迭代终值。</param>
    /// <param name="eps">eps控制精度要求。</param>
    /// <param name="inter">最多迭代次数</param>
    /// <returns>函数返回迭代次数。程序最多迭代次数为500。</returns>
    public static unsafe int atkn(double* x, double eps, int inter = 500)
    {
        int flag, k;
        double u, v, x0;

        k = 0;
        x0 = *x;
        flag = 0;
        while ((flag == 0) && (k < inter))
        {
            k = k + 1;
            u = f_x(x0);
            v = f_x(u);
            if (Math.Abs(u - v) < eps)
            {
                x0 = v;
                flag = 1;
            }
            else
            {
                x0 = v - (v - u) * (v - u) / (v - 2.0 * u + x0);
            }
        }
        *x = x0;
        return (k);
    }

    /*
    // 方程求根aitken迭代法例
      int main()
      { 
          int k;
          double x,eps,atknf(double);
          eps = 0.0000001;  x = 0.0;
          k = atkn(&x,eps,atknf);
          cout <<"迭代次数 = " <<k <<endl;
          cout <<"迭代终值 x = " <<x <<endl;
          return 0;
      }
    // φ(x)
      double atknf(double x)
      { 
          return(6.0-x*x);
      }
    */
}

